﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HorseRaceRe.UI;
using XQColorful.SDK;
using XQColorful.SDK.EventArgs;
using XQColorful.SDK.Interface;
using XQColorful.SDK.Models;

namespace HorseRaceRe.Code.Events
{
    public class EventStartRace : IPluginEvent
    {
        public XQEventType EventType => XQEventType.Group;

        public void Process(XQEventArgs _e)
        {
            var e = new GroupMsgEventArgs(_e);

            if (e.Message == "开始赛马")
            {
                var msg = new StringBuilder();

                if (App.GroupGrounds.ContainsKey(e.FromGroup))
                {
                    if (App.GroupGrounds[e.FromGroup].Horses.Count >= App.AppSet.MinJoin)
                    {
                        StartRace(e, e.FromGroup);
                    }
                }
                else
                {
                    msg.AppendLine("本群还未开始赛马比赛!");
                }
            }
        }

        public static void StartRace(GroupMsgEventArgs e, string group)
        {
            App.TaskList.Add(Task.Factory.StartNew(async () =>
            {
                var ground = App.GroupGrounds[group];
                ground.Start();
                var msg = ground.GenerateStr(null);
                e.SendMsg($"{msg}\n" + "比赛开始了!");

                await Task.Delay(6000);
                List<string> strs;

                while (!ground.Process(out strs,true))
                {
                    msg = ground.GenerateStr(strs);
                    e.SendMsg(msg);
                    await Task.Delay(6000);
                }

                msg = ground.GenerateStr(strs);
                e.SendMsg(msg + "比赛结束!");
                
                App.GroupGrounds.Remove(group);
            }));
        }
    }
}